﻿using AutoMapper;
using Ross.EntityFramework;
using Ross.EntityFramework.Model;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Ross.Service
{
    public class MonthlyPlanService : BaseService, IDisposable
    {
        private TranDbContext dbContext;
        public IRepository<Targets, int> repository;
        public IRepository<Users, int> repository2;

        public MonthlyPlanService(string nameOrConnectionString)
        {
            dbContext = new TranDbContext(nameOrConnectionString);
            repository = new Repository<Targets, int>(dbContext);
            repository2 = new Repository<Users, int>(dbContext);
        }

        /// <summary>
        /// 返回登录时选择的年份对应员工可查阅的所有部门的所有计划信息
        /// </summary>
        /// <returns></returns>
        public ResultDto<List<Dto.MonthlyPlan>> Get()
        {
            ResultDto<List<Dto.MonthlyPlan>> result = new ResultDto<List<Dto.MonthlyPlan>>();
            
            try
            {
                //var currtUser = Thread.CurrentPrincipal;
                if (!string.IsNullOrEmpty(username))
                {
                    //string username = currtUser.Identity.Name.Split(':')[0];
                    //string year = DateTime.Parse(currtUser.Identity.Name.Split(':')[1]).ToString("yyyy");
                    var obj1 = repository2.GetAllList(o => o.UserName == username || o.EmpID == username).FirstOrDefault();
                    string[] departments = obj1.AuthorizedDepartment.Split(',');
                    var obj = repository.GetAllList(o => o.StartingTime.Year == year && departments.Contains(o.Department) && o.Depth >= 3 && o.ApprovalStatus == "已审核").ToList();
                    
                    if (obj != null)
                    {
                        result.status = 200;
                        result.datas = Mapper.Map<List<Dto.MonthlyPlan>>(obj);
                    }
                    else
                    {
                        result.message = "user is not exist";
                        result.status = 500;
                    }
                }
                else
                {
                    result.message = "Unable to access unauthorized app";
                    result.status = 500;
                }
            }
            catch (Exception e)
            {
                result.message = e.Message;
                result.status = 500;
            }
            return result;

        }

        /// <summary>
        /// 根据条件返回对应数据
        /// </summary>
        /// <param name="month">月份</param>
        /// <param name="week">周</param>
        /// <param name="department">部门</param>
        /// <param name="Responsible">责任人</param>
        /// <returns></returns>
        public ResultDto<List<Dto.MonthlyPlan>> Get(string month = "",string week = "",string department = "",string Responsible = "")
        {
            ResultDto<List<Dto.MonthlyPlan>> result = new ResultDto<List<Dto.MonthlyPlan>>();
            Expression<Func<Targets, bool>> expression = o => o.ID > 0;
            try
            {
                //var currtUser = Thread.CurrentPrincipal;
                if (!string.IsNullOrEmpty(username))
                {
                    var obj1 = repository2.GetAllList(o => o.UserName == username || o.EmpID == username).FirstOrDefault();
                    string[] departments = obj1.AuthorizedDepartment.Split(',');
                    expression = expression.ExpressionAnd(o => o.StartingTime.Year == year);
                    if (!string.IsNullOrEmpty(month))
                    {
                        int m = int.Parse(month);
                        expression = expression.ExpressionAnd(o => o.StartingTime.Year == year && o.StartingTime.Month == m);                        
                    }
                    if (!string.IsNullOrEmpty(week))
                    {
                        Tuple<DateTime, DateTime> tuple = GetFirstEndDayOfWeek(year, int.Parse(week));
                        DateTime start = DateTime.Parse(tuple.Item1.ToString("yyyy-MM-dd"));
                        DateTime end = DateTime.Parse(tuple.Item2.ToString("yyyy-MM-dd"));
                        expression = expression.ExpressionAnd(o => o.PlannedCompletionTime >= start && o.PlannedCompletionTime <= end);
                    }
                    if (!string.IsNullOrEmpty(department))
                        expression = expression.ExpressionAnd(o => o.Department == department);
                    else
                        expression = expression.ExpressionAnd(o => departments.Contains(o.Department));
                    if (!string.IsNullOrEmpty(Responsible))
                        expression = expression.ExpressionAnd(o => o.Responsible == Responsible);
                    expression = expression.ExpressionAnd(o => o.ApprovalStatus == "已审核" && o.Depth >= 3);
                    var obj = repository.GetAllList(expression).ToList();

                    if (obj != null)
                    {
                        result.status = 200;
                        result.datas = Mapper.Map<List<Dto.MonthlyPlan>>(obj);
                    }
                }
                else
                {
                    result.message = "user is not exist";
                    result.status = 500;
                }
            }
            catch (Exception e)
            {
                result.message = e.Message;
                result.status = 500;
            }
            return result;
        }

        public void Dispose()
        {
            dbContext.Dispose();
        }

        /// <summary>
        /// 根据一年中的第几周获取该周的开始日期与结束日期
        /// </summary>
        /// <param name="year"></param>
        /// <param name="weekNumber"></param>
        /// <param name="culture"></param>
        /// <returns></returns>

        public static Tuple<DateTime, DateTime> GetFirstEndDayOfWeek(int year, int weekNumber)
        {
            CultureInfo culture = CultureInfo.GetCultureInfo("zh-cn");
            System.Globalization.Calendar calendar = culture.Calendar;
            DateTime firstOfYear = new DateTime(year, 1, 1, calendar);
            DateTime targetDay = calendar.AddWeeks(firstOfYear, weekNumber - 1);
            DayOfWeek firstDayOfWeek = culture.DateTimeFormat.FirstDayOfWeek;
            while (targetDay.DayOfWeek != firstDayOfWeek)
            {
                targetDay = targetDay.AddDays(-1);
            }
            return Tuple.Create<DateTime, DateTime>(targetDay, targetDay.AddDays(6));
        }
    }
}
